package com.mz.ieann.aide.base.vb

import android.app.Activity
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import androidx.annotation.LayoutRes
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import com.mz.ieann.aide.base.BaseActivity
import java.lang.reflect.ParameterizedType

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> viewModel+viewBinding
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2021/12/5
 */
abstract class BaseVBActivity<VM : ViewModel>(@LayoutRes val resourceId : Int) : BaseActivity() {

    /**
     * ViewModel
     */
    protected val viewModel : VM by lazy {
        val vmClass = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VM>
        ViewModelProvider(this).get(vmClass)
    }

    /**
     * 子类调用
     */
    inline fun <reified VB : ViewBinding> Activity.inflate() = lazy {
        inflateBinding<VB>(layoutInflater).apply { setContentView(root) }
    }

    /**
     * 子类调用
     */
    inline fun <reified VB : ViewBinding> Dialog.inflate() = lazy {
        inflateBinding<VB>(layoutInflater).apply { setContentView(root) }
    }

    /**
     * ViewBinding
     */
    inline fun <reified VB : ViewBinding> inflateBinding(layoutInflater: LayoutInflater) =
        VB::class.java.getMethod("inflate", LayoutInflater::class.java).invoke(null, layoutInflater) as VB

    override fun onCreate(savedInstanceState: Bundle?) {
        createBefore()
        super.onCreate(savedInstanceState)
        setContentView(resourceId)
        initActivity()
    }

    open fun createBefore(){

    }

    abstract fun initActivity()

}